package com.heima.mobile.controller;

import com.heima.dto.PhoneCodeDto;
import com.heima.dto.PhoneDto;
import com.heima.mobile.service.UserService;
import com.heima.mobile.thread.TokenThreadUtils;
import com.heima.pojo.User;
import com.heima.vo.LoginVo;
import com.heima.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;


/**
 * @author itheima
 * @since 2022-11-28
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public Result sendMsg(@RequestBody PhoneDto phoneDto) {
        Boolean result = userService.sendMsg(phoneDto.getPhone());

        return new Result(result ? 200 : 500, result ? "发送成功" : "发送失败", null);
    }

    @PostMapping("/login")
    public Result login(@RequestBody PhoneCodeDto phoneCodeDto) {
        LoginVo login = userService.login(phoneCodeDto);
        return new Result(200, "登录成功", login);
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("/test")
    public Result test(String name) {

        if (StringUtils.isEmpty(name)) {
            throw new RuntimeException("name不能为空");
        }

        // 我想在这打印当前登录用户的id
        User userInfo = TokenThreadUtils.getThreadLocal();
        if (userInfo == null) {
            return null;
        }

        System.out.println("用户id:" + userInfo.getId());

        // 4. 如果查到了，就放行
        return new Result(200, "ok", null);
    }

}
